// TapboxA 管理自身状态.

//------------------------- TapboxA ----------------------------------

import 'package:flutter/material.dart';

// ParentWidget 为 TapboxB 管理状态.

//------------------------ ParentWidget --------------------------------

class ManageStateParentWidget extends StatefulWidget {
  const ManageStateParentWidget({super.key});

  @override
  _ManageStateParentWidgetState createState() => _ManageStateParentWidgetState();
}

class _ManageStateParentWidgetState extends State<ManageStateParentWidget> {
  bool _active = false;

  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TapboxB(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}

//------------------------- TapboxB ----------------------------------

class TapboxB extends StatelessWidget {
  TapboxB({Key? key, this.active= false, required this.onChanged})
      : super(key: key);

  final bool active;
  final ValueChanged<bool> onChanged;

  ///TapboxB通过回调将其状态导出到其父组件，状态由父组件管理
  void _handleTap() {
    onChanged(!active);
  }

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: Container(
        child: Center(
          child: Text(
            active ? 'A' : 'B',
            style: TextStyle(fontSize: 32.0, color: Colors.white),
          ),
        ),
        width: 200.0,
        height: 200.0,
        decoration: BoxDecoration(
          color: active ? Colors.lightGreen[700] : Colors.grey[600],
        ),
      ),
    );
  }
}